package Demo1_26;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-26
 * Time:16:07
 */
// 定义二叉树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }
}

public class BinaryTreePostorderTraversal {
    // 后序遍历方法
    public static void postorderTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        // 递归遍历左子树
        postorderTraversal(root.left);
        // 递归遍历右子树
        postorderTraversal(root.right);
        // 访问根节点
        System.out.print(root.val + " ");
    }

    public static void main(String[] args) {
        // 构建一个简单的二叉树
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        // 调用后序遍历方法
        System.out.print("后序遍历结果: ");
        postorderTraversal(root);
    }
}